<?php
class Router{
    private static $routes=null;

    public static function getRoutes(){
        $routeFile=Util::getRootDirectory()."/store/route.json";

        if (!file_exists($routeFile)){
            Res::error(500,'没有找到route文件: '.$routeFile);
            exit();
        }

        self::$routes=json_decode(file_get_contents($routeFile),true);
        if (self::$routes === null){
            Res::error(500,'没有设置或JSON格式错误');
            exit();
        }
    }
    
    public static function exe($method,$uri){
        // handle the options
        if ($method==="options"){
            header('HTTP/1.1 200 OK');
            exit();
        }

        if (self::$routes===null){
            self::getRoutes();
        }

        $uri=strtolower(explode('?',$uri)[0]);
        foreach(self::$routes as $route)
        {
            // 判断谓词是否相同
            if ($method!==strtolower($route['method'])){
                continue;
            }

            // route uri数组 和 uri数组
            $routeUrts=explode('/',$route['uri']);
            $urts=explode('/',$uri);

            // var_dump($routeUrts,$urts);

            // 判断uri段落长度是否相等
            if (count($urts)!==count($routeUrts)){
                continue;
            }

            $params=array();
            $lastIndex=0;

            foreach($routeUrts as $index=>$urt){
                if (substr($urt,0,1)==='{' && substr($urt,-1)==='}'){
                    array_push($params,$urts[$index]);
                    $lastIndex=$index;
                }else{
                    if ($urt===$urts[$index]){
                        $lastIndex=$index;
                    }else{
                        break;
                    }
                }
            }
            
            if ($lastIndex===count($routeUrts)-1){
                Mid::beforeRoute($route);
                self::core($route,$params);
                return '';
            }

            
        }
        header('HTTP/1.1 404 Not Found');
        echo '404 NOT FOUND';
        return '';
    }

    public static function core($route,$params){

        $obj=new $route["class"]();
        return call_user_func_array(array($obj,$route["function"]),$params);
    }
}
